<template>
  <div class="carousel-management">
    <h2>轮播图管理</h2>
    <button class="add-btn" @click="openAddModal">添加轮播图</button>
    <table v-if="carouselImages.length > 0">
      <thead>
      <tr>
        <th>ID</th>
        <th>图片</th>
        <th>标题</th>
        <th>链接</th>
        <th>排序</th>
        <th>状态</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="item in carouselImages" :key="item.carouselId">
        <td>{{ item.carouselId }}</td>
        <td><img :src="item.imageUrl" alt="轮播图" class="thumbnail" /></td>
        <td>{{ item.title || '无' }}</td>
        <td>{{ item.link || '无' }}</td>
        <td>{{ item.sortOrder }}</td>
        <td>{{ item.isActive ? '启用' : '禁用' }}</td>
        <td>
          <button @click="openEditModal(item)">编辑</button>
          <button @click="deleteCarouselImage(item.carouselId)">删除</button>
        </td>
      </tr>
      </tbody>
    </table>
    <p v-else>暂无轮播图数据</p>

    <div v-if="showModal" class="modal">
      <div class="modal-content">
        <h3>{{ isEdit ? '编辑轮播图' : '添加轮播图' }}</h3>
        <form @submit.prevent="saveCarouselImage">
          <div>
            <label>图片:</label>
            <input
                type="file"
                ref="imageInput"
                @change="handleImageUpload"
                accept="image/*"
                :required="!isEdit"
            />
            <img v-if="form.imageUrl" :src="form.imageUrl" class="preview" />
          </div>
          <div>
            <label>标题:</label>
            <input v-model="form.title" type="text" placeholder="可选" />
          </div>
          <div>
            <label>链接:</label>
            <input v-model="form.link" type="text" placeholder="可选" />
          </div>
          <div>
            <label>排序:</label>
            <input v-model.number="form.sortOrder" type="number" min="0" required />
          </div>
          <div>
            <label>状态:</label>
            <select v-model="form.isActive" required>
              <option :value="true">启用</option>
              <option :value="false">禁用</option>
            </select>
          </div>
          <div class="modal-actions">
            <button type="submit">保存</button>
            <button type="button" @click="closeModal">取消</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      carouselImages: [],
      showModal: false,
      isEdit: false,
      form: {
        carouselId: null,
        imageUrl: '',
        title: '',
        link: '',
        sortOrder: 0,
        isActive: true,
        imageFile: null
      }
    };
  },
  mounted() {
    this.fetchCarouselImages();
  },
  methods: {
    async fetchCarouselImages() {
      try {
        const response = await axios.get(axios.defaults.baseURL+'/api/carousel/all', {
          headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` }
        });
        this.carouselImages = response.data;
      } catch (error) {
        console.error('获取轮播图失败:', error);
        const message = error.response?.data?.message || '获取轮播图失败';
        if (message.includes('只有超级管理员可以操作轮播图')) {
          alert('权限不足：只有超级管理员可以查看和管理轮播图');
          this.$router.push('/admin/dashboard');
        } else {
          alert(message);
        }
      }
    },
    openAddModal() {
      this.isEdit = false;
      this.form = {
        carouselId: null,
        imageUrl: '',
        title: '',
        link: '',
        sortOrder: 0,
        isActive: true,
        imageFile: null
      };
      this.showModal = true;
    },
    openEditModal(item) {
      this.isEdit = true;
      this.form = { ...item, imageFile: null };
      this.showModal = true;
    },
    closeModal() {
      this.showModal = false;
      this.$refs.imageInput.value = '';
    },
    handleImageUpload(event) {
      const file = event.target.files[0];
      if (file) {
        this.form.imageUrl = URL.createObjectURL(file);
        this.form.imageFile = file;
        console.log('已选择图片:', file.name, '大小:', file.size);
      }
    },
    async saveCarouselImage() {
      const formData = new FormData();
      const dto = {
        title: this.form.title,
        link: this.form.link,
        sortOrder: this.form.sortOrder,
        isActive: this.form.isActive
      };

      // 将dto转换为Blob并指定Content-Type
      const dtoBlob = new Blob([JSON.stringify(dto)], { type: 'application/json' });
      formData.append('dto', dtoBlob, 'dto.json'); // 指定文件名确保正确识别类型

      if (this.form.imageFile) {
        formData.append('image', this.form.imageFile);
      } else if (!this.isEdit) {
        alert('请上传图片');
        return;
      }

      console.log('发送的 FormData:');
      for (let [key, value] of formData.entries()) {
        console.log(`${key}:`, value);
      }

      try {
        const config = {
          headers: {
            Authorization: `Bearer ${sessionStorage.getItem('token')}`,
            'Content-Type': 'multipart/form-data' // 明确设置，与成功的 uploadAvatar 一致
          }
        };
        if (this.isEdit) {
          await axios.put(axios.defaults.baseURL+`/api/carousel/${this.form.carouselId}`, formData, config);
          alert('轮播图更新成功');
        } else {
          const response = await axios.post(axios.defaults.baseURL+'/api/carousel/create', formData, config);
          console.log('后端响应:', response.data);
          alert('轮播图添加成功');
        }
        this.fetchCarouselImages();
        this.closeModal();
      } catch (error) {
        console.error('保存轮播图失败:', error);
        const status = error.response?.status;
        const message = error.response?.data?.message || `保存失败: ${error.message}`;
        if (message.includes('只有超级管理员可以操作轮播图')) {
          alert('权限不足：只有超级管理员可以操作轮播图');
          this.$router.push('/admin/dashboard');
        } else if (status === 415) {
          alert('文件格式错误：请确保上传的文件是支持的图片格式，或检查服务器配置');
        } else {
          alert(message);
        }
      }
    },
    async deleteCarouselImage(carouselId) {
      if (confirm('确定删除此轮播图吗？')) {
        try {
          await axios.delete(axios.defaults.baseURL+`/api/carousel/${carouselId}`, {
            headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` }
          });
          alert('轮播图删除成功');
          this.fetchCarouselImages();
        } catch (error) {
          console.error('删除轮播图失败:', error);
          const message = error.response?.data?.message || '删除失败';
          if (message.includes('只有超级管理员可以操作轮播图')) {
            alert('权限不足：只有超级管理员可以操作轮播图');
            this.$router.push('/admin/dashboard');
          } else {
            alert(message);
          }
        }
      }
    }
  }
};
</script>

<style scoped>
/* 保持不变，与之前一致 */
.carousel-management {
  padding: 20px;
}

.add-btn {
  background-color: #007bff;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-bottom: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th, td {
  border: 1px solid #ddd;
  padding: 10px;
  text-align: center;
}

.thumbnail {
  max-width: 100px;
  max-height: 50px;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 10px;
  width: 400px;
}

form div {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
}

input, select {
  width: 100%;
  padding: 5px;
  box-sizing: border-box;
}

.preview {
  max-width: 100px;
  margin-top: 10px;
}

.modal-actions {
  display: flex;
  gap: 10px;
}

.modal-actions button {
  padding: 10px;
  flex: 1;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.modal-actions button[type="submit"] {
  background-color: #007bff;
  color: white;
}

.modal-actions button[type="button"] {
  background-color: #ccc;
  color: black;
}
</style>